package com.lhh.springcommon.aspect;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhh.springcommon.annotation.WebLog;
import com.lhh.springcommon.mapper.UserMapper;
import com.lhh.springcommon.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * AOP日志管理
 * @author 李厚航
 */
@Aspect
@Component
@Slf4j
public class LoggingAspect {

    @Around("@annotation(webLog)")
    public Object logAround(ProceedingJoinPoint joinPoint, WebLog webLog) throws Throwable {
        String methodSignature = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        String methodParameters = Arrays.toString(joinPoint.getArgs());

        // 记录方法调用前的日志
        log.info("Before method: {}, Parameters: {}", methodSignature, methodParameters);

        long startTime = System.currentTimeMillis();
        Object result = null;
        try {
            // 执行目标方法
            result = joinPoint.proceed();
            return result;
        } catch (Throwable ex) {
            // 记录异常日志
            log.error("Exception in method: {}, Error: {}", methodSignature, ex.getMessage(), ex);
            // 重新抛出异常
            throw ex;
        } finally {
            if (result instanceof Page) {
                Page<?> page = (Page<?>) result;
                result = page.getRecords();
            }
            // 记录方法调用后的日志
            long executionTime = System.currentTimeMillis() - startTime;
            log.info("After method: {}, Execution time: {} ms, Result: {}", methodSignature, executionTime, result);
        }
    }
}
